package com.moose.operator.feign;

import com.moose.operator.exception.BusinessException;
import com.moose.operator.model.api.ResultCode;
import com.moose.operator.util.MapperUtils;
import feign.Response;
import feign.codec.ErrorDecoder;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

/**
 * <p>
 * Description:
 * </p>
 *
 * @author taohua
 * @version v1.0.0
 * @date 2021-01-02 10:55:10:55
 * @see com.moose.operator.feign
 */
@Slf4j
public class DefaultErrorDecoder implements ErrorDecoder {

  @Override public Exception decode(String s, Response response) {
    String content = null;
    try {
      InputStream inputStream = response.body().asInputStream();
      content = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
      log.error(content);
      Map<String, Object> result = MapperUtils.json2map(content);
      if (null == content || result.isEmpty()) {
        return new BusinessException(ResultCode.AUTH_SERVER_ERROR);
      }
      String message = (String) result.get("message");
      Integer code = (Integer) result.get("code");
      return new BusinessException(message, code);
    } catch (Exception exception) {
      log.error(exception.getMessage());
      return new BusinessException(ResultCode.AUTH_SERVER_ERROR);
    }
  }
}
